<template>
  <view class="scl-search-page"
    
  >
  <!-- :style="{backgroundImage:'url('+staticImgs.pageBg+')'}" -->
    <view>
      <view class="top-wrapper">
        <!-- <view class="top-bg-wrapper">
          <view class="top-bg-abs">
            <image class="img" :src="staticImgs.pageBg" ></image>
          </view>
        </view> -->

          <view class="row-1"
          :style="{backgroundImage:'url('+staticImgs.pageBg+')'}"
          >
            <!-- <view class="left-coupon"
              :style="{backgroundImage:'url('+staticImgs.couponBg+')'}"
            >
              {{couponInfo.text}}券
            </view> -->
            
            <view class="coupon-item"
              :style="{backgroundImage:'url('+staticImgs.couponBg+')'}"
            >
              <view class="row-1">{{couponInfo.text}}</view>
              <view class="row-2">测评券</view>
              <view class="row-3"></view>
            </view>
<!--               :style="{backgroundImage:'url('+staticImgs.img1+')'}" -->            
            <view class="right-clock">
              <view class="content-left">
                <view class="tip-text">仅剩</view>
                <u-count-down
                  @finish="countDownFinishHandle" 
                  :time="countdownMillis" 
                  format="HH:mm:ss"
                  autoStart
                  millisecond
                  @change="onTimeChange"
                >
                  <view class="time">
                      <view class="time__custom" :style="{backgroundImage:'url('+staticImgs.numBg+')'}">
                          <text class="time__custom__item">{{ timeData.hoursArr[0] }}</text>
                      </view>
                      <view class="time__custom m-l-abs-3" :style="{backgroundImage:'url('+staticImgs.numBg+')'}">
                          <text class="time__custom__item">{{ timeData.hoursArr[1]}}</text>
                      </view>
                      <view class="time__custom m-l-abs-3" v-show="timeData.hoursArr && timeData.hoursArr.length == 3" :style="{backgroundImage:'url('+staticImgs.numBg+')'}">
                          <text class="time__custom__item">{{ timeData.hoursArr[2] }}</text>
                      </view>
                      <text class="time__doc">:</text>
                      <view class="time__custom " :style="{backgroundImage:'url('+staticImgs.numBg+')'}">
                          <text class="time__custom__item">{{ timeData.minutesArr[0] }}</text>
                      </view>
                      <view class="time__custom m-l-abs-3" :style="{backgroundImage:'url('+staticImgs.numBg+')'}">
                          <text class="time__custom__item">{{ timeData.minutesArr[1]}}</text>
                      </view>
                      <text class="time__doc">:</text>
                      <view class="time__custom" :style="{backgroundImage:'url('+staticImgs.numBg+')'}">
                          <text class="time__custom__item">{{ timeData.secondsArr[0] }}</text>
                      </view>
                      <view class="time__custom m-l-abs-3" :style="{backgroundImage:'url('+staticImgs.numBg+')'}">
                          <text class="time__custom__item">{{ timeData.secondsArr[1]}}</text>
                      </view>
                  </view>
                </u-count-down>
              </view>
            </view>
          </view>
          
        
      </view>
      <view class="menu-wrapper-container" >
          <scroll-view class="scroll-menu" scroll-x scroll-with-animation>
            <view class="menu-wrapper">
              <view class="menu-box" v-for="(item,index) in menuList" :key="index"
                :id="'scv'+index" :class="{'menu-box-act': index === currentMenuIndex,'menu-box-act-2':index === currentMenuIndex && item.bg ,'menu-item-bg':item.bg}"
                @click="changeSclMenu(index)"
              >
                <!-- <image style="width: 152rpx;" v-if="item.bg" :src="item.bg" mode="widthFix"></image> -->
                
                <text >{{item.label}}</text>
              </view>
            </view>
          </scroll-view>
        </view>
      
      
      <view class="main-content-wrapper">

          
          <mescroll-body  
            ref="mescrollRef" @init="mescrollInit" 
            @down="downCallback" @up="fetchSclData" :down="downOption" 
            :up="upOption" :top="50"
            
          >        
            <SclBox 
              isShowBg :discountType="discountType" :discountNum="discountNum" 
              @clickBox="()=>checkNotCompleteScl(item.id,()=>itemClick(item))" 
              v-for="item in dataList" :sclData="item" :key="item.id"
            />
          </mescroll-body>
            

      </view>
      
    </view>
  </view>
</template>

<script>
  import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
  import SclBox from '@/components/SclBox.vue'
  import {mapGetters,mapState} from 'vuex'
  import {calculateDiscountedPrice} from '@/common/utils/util.js'
  import sclNotCompleteMixin from '@/mixins/sclNotCompleteMixin.js'
  import {
  	get_recommend_scl_list,
  	get_more_scl_list,
    getMoreSclInfo
  } from '@/common/api/scl_api.js'
  export default {
    mixins: [MescrollMixin,sclNotCompleteMixin],
    components:{
      SclBox
    },
    data() {
      return {
        dataList:[],
        currentMenuIndex:0,
        upOption: {
        	isBounce: true,
        	auto: false,
        	page: {
        		size: 10 // 每页数据的数量,默认10
        	},
        	noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
        	empty: {
        		icon: '/static/images/img_no_data_order.png',
        		tip: '暂无更多测评'
        	}
        },
        currentType:'recommend',
        staticImgs:{
          pageBg: this.imgBaseURL + '/scl/img-c-bg-v5.png',
          img1: this.imgBaseURL + '/scl/img-c-2.png',
          couponBg: this.imgBaseURL + '/scl/coupon-item-bg.png',
          // couponBg: this.imgBaseURL + '/scl/coupon-item-bg-2.png',
          numBg: this.imgBaseURL + '/scl/count-down-time-box-v3.png',
        },
        pageDiscountId:'',
        scrollHeight:0,
        countdownMillis:0,
        timeData: {
          hoursArr:[],
          minutesArr:[],
          secondsArr:[]
        },
        couponList:[],
        couponInfo:{},
        menuList:[
          {
            label:'为你推荐',
            val:'recommend',
          },
          {
            label:'全部',
            val:''
          },
          {
            label:'热卖排行',
            val:'hot'
          },
          {
            label:'抑郁专题',
            val:'c2660b89d38a22e38ca5e3f5de1625ca',
            bg:this.imgBaseURL + '/scl/scl-category-yy.png',
          },
          {
            label:'青少年专题',
            val:'e9f42d5d0aa54157ae3ac11e89e61719',
          }
        ],
      }
    },
    watch:{
      clientUserUid:{
        handler(val){
          if(val){
            this.shareData.path = '/pages/index/index?userType=sclList&inviteId='+val
          }
        },
        immediate:true
      },
    },
    computed:{
      ...mapGetters('user',['clientUserUid']),
      ...mapState({
        currentGroup:state => state.user.currentGroup,
        discountNum:state => state.user.discountNum,
        discountId:state => state.user.discountId,
        discountType:state => state.user.discountType,
      }),
    },
    onLoad(opt) {
      this.pageDiscountId = opt.id
      //获取页面高度 - 390rpx
      
      const pageHeight = uni.getSystemInfoSync().windowHeight;
      this.scrollHeight = pageHeight - this.rpxToPx(390);
      
      this.initDiscountCountDown()
    },
    methods: {
      changeSclMenu(index){
        this.currentMenuIndex = index
        this.dataList = []
      
        this.mescroll.resetUpScroll(true)
        
        const query = uni.createSelectorQuery().in(this)
        query.select('#main-content-wrapper').boundingClientRect(data => {
          setTimeout(()=>{
            // this.mescroll.scrollTo(0,120) // 重置列表数据为第一页时,建议把滚动条也重置到顶部,避免无法再次翻页的问题  
          },250)
        }).exec()
      }, 
      async initDiscountCountDown(){
        const {data:dRes} = await this.$u.api.getUserActCouponList({
          status:1,
          num:2
        })
        
        if(dRes.data){
          const tmpArr = []
          dRes.data.map(item=>{
            tmpArr.push({
              // item.
               text:item.discountType === 1  ? `${item.discount}折` : `${item.immediately}元`,
               ...item
            })
          })
          this.couponList = tmpArr
          
          this.couponInfo = this.couponList.find(item=>item.discountUid===this.pageDiscountId)
          this.$store.commit('user/setActCouponCode',this.couponInfo.code)
          this.$store.commit('user/setActCouponId',this.couponInfo.discountUid)
          
          console.log(this.$store,'======$store=====')
          
          // dRes.data = dRes.data[0]
          
          // 优惠券的获取时间
          const couponStartTime = this.$dayjs(this.couponInfo.getTime); // 假设获取时间为 "2023-11-02 08:00:00"
          console.log(this.couponInfo,'====dRes.data------')
          // 有效小时数
          const validHours = this.couponInfo.validNumber; // 假设有效小时数为 24 小时
          
          // 计算到期时间
          const couponEndTime = couponStartTime.add(validHours, 'hour');
          
          // 获取到期时间的毫秒数
          const couponEndTimeMillis = couponEndTime.valueOf();
          
          // 获取当前时间的毫秒数
          const currentTimeMillis = this.$dayjs().valueOf();
          
          // 计算倒计时剩余毫秒数
          this.countdownMillis = couponEndTimeMillis - currentTimeMillis;
        }
      },
      backPage(){
        uni.navigateBack()
      },
      countDownFinishHandle(){
        console.log('------countDownFinishHandle------')
      },
      onTimeChange(e) {
          // 计算总小时数并格式化为两位数
          const tmpH = e.hours + (e.days * 24);
          this.timeData = {
              hours: tmpH > 9 ? String(tmpH) : '0' + tmpH,
              minutes: e.minutes > 9 ? String(e.minutes) : '0' + e.minutes,
              seconds: e.seconds > 9 ? String(e.seconds) : '0' + e.seconds,
              hoursArr: String(tmpH).padStart(2, '0').split(''),
              minutesArr: String(e.minutes).padStart(2, '0').split(''),
              secondsArr: String(e.seconds).padStart(2, '0').split('')
          };
      },
      itemClick(item) {
      	if (item.reportId) {
      		uni.navigateTo({
      			url: '/subcontractorB/pages/sclResult/sclResult?reportId=' + item.reportId + '&sclId=' +
      				item.id
      		})
      	} else {
          
          this.$u.api.addLog({sclId:item.id,sourseType:this.currentType == '' ? 12 : 13})
      		uni.navigateTo({
      			url: '/subcontractorC/pages/sclIntroduce/sclIntroduce?paramObj=' + JSON.stringify({
      				sclId: item.id,
              actCouponCode:this.couponInfo.code
      			})
      		})
      	}
      },
      searchHandle(){
        console.log('AAAAAAAA')
        if(this.$fangBaoClick()){
          return 
        }
        console.log('searchHandle ====')
        this.mescroll.resetUpScroll()
      },
      async fetchSclData(page) {
      	if (page.num == 1) this.dataList = [];
      
        const menuItem = this.menuList[this.currentMenuIndex]
        
        if(!this.couponInfo.code){
          await this.initDiscountCountDown()
        }
        
        const queryParam = {
          pageNo: page.num,
          pageSize: page.size,
          group: this.currentGroup,
          code: this.couponInfo.code
        }
        
        if(menuItem.val == 'recommend'){
          queryParam['recommend'] = 'Y'
        }else if (menuItem.val == 'hot'){
          queryParam['ranking'] = 'Y'
        }else if (menuItem.val){
          queryParam['consultLabelUid'] = menuItem.val
        }

      	const {
      		data: dRes
      	} = await this.$u.api.getSclList(queryParam)
      
      	console.log('测评数据：', dRes)
      
      	if (dRes.code === 200) {
      		const {
      			records = []
      		} = dRes.data
      		const datas = this.dataProcess(records)
      		if (this.dataList.length > 0) {
      			this.dataList = this.dataList.concat(datas)
      		} else {
      			this.dataList = datas
      		}
      		this.mescroll.endBySize(records.length, dRes.data.total);
      	} else {
      		this.$showToast("请求获取选择问题接口失败," + dRes.message)
      	}
        this.currentType = ''
      },
      dataProcess(rows){
        const tmpArr = []
        rows.map(item => {
            const tmpObj = JSON.parse(JSON.stringify(item))
            tmpObj.coverImg = item.coverImg||item.detailImg
            tmpObj.sclName = item.sclName||item.scl_name
            tmpObj.summary = item.summary||item.nickName
            
            /*
            if(this.discountId){
              console.log('dc-折扣前：',tmpObj.newOriginalPrice)
              tmpObj.originalPrice = item.newOriginalPrice
              tmpObj.newOriginalPrice = calculateDiscountedPrice(item.newOriginalPrice,this.discountNum)
              
              console.log('dc-折扣后：',tmpObj.newOriginalPrice)
            }
            */
            
            tmpArr.push(tmpObj)
        })
        return tmpArr
      },
    }
  }
</script>

<style lang="scss" scoped>
  /deep/.input-placeholder {
    font-size: 26rpx;
    font-family: PingFang-SC;
    font-weight: 500;
    color: rgba(190, 187, 187, .82);
  }
  /deep/.scl-box{
    margin-left: 12rpx;
    margin-right: 12rpx;
    width: 728rpx !important;
  }
  
  /deep/.mescroll-body{
    padding-top: 12rpx !important;
  }

  .scl-search-page {
    background-repeat: no-repeat;
    // padding-top: 390rpx;
    background-size: 100% 720rpx;
    background-attachment: fixed;
    height: 100vh;
    // overflow: hidden;
    position: relative;
    
    background-color: #f8f8f7;
    
        width: 100vw;
            overflow-x: hidden;

    
    
    .top-wrapper{
      // position: fixed;
      // top: 0;
      // z-index: 8;
      
      background-repeat: no-repeat;
      background-size: 100% 720rpx;
      background-attachment: fixed;
      
      width: 750rpx;
      box-sizing: border-box;
      
      background-color: #f8f8f7;

      
      .top-bg-wrapper{
        position: relative;
        width: 100%;
        .top-bg-abs{
          position: absolute;
          top: 0;
          left: 0;
          width: 750rpx;
          height: 460rpx;
          overflow: hidden;
          .img{
            width: 100%;
            height: 720rpx;
          }
        }
      }
      

        >.row-1{
          // display: flex;
          // position: absolute;left: 0;
          // top: 0;
          
              display: flex;
              align-items: flex-end;
              // justify-content: center;
              // padding-left: 78rpx;
              
              background-repeat: no-repeat;
              background-size: 100% 100%;
              height: 390rpx;
              width: 100%;
              box-sizing: border-box;
              
              padding-bottom: 30rpx;
          
        }
      
      
      
      
      .left-coupon{
        font-family: PingFang-SC, PingFang-SC;
        font-weight: 800;
        font-size: 50rpx;
        color: #FF4E70;
        line-height: 70rpx;
        text-align: center;
        font-style: normal;
        
        width: 240rpx;
        height: 144rpx;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        margin-left: 74rpx;
        margin-top: 220rpx;
        
        line-height: 144rpx;
      }
      
      .coupon-item{
            margin-bottom: -12rpx;

        margin-left: 114rpx;
          background-repeat: no-repeat;
          background-size: 100% 100%;
          width: 168rpx;
          height: 180rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          // justify-content: center;
          
          .row-1{
            font-family: PingFang-SC, PingFang-SC;
            font-weight: 800;
            font-size: 40rpx;
            color: #FF4E70;
            line-height: 56rpx;
            text-align: left;
            font-style: normal;
            
            margin-top: 18rpx;
          }
          
          .row-2{
            margin-top: -8rpx;
            font-family: PingFang-SC, PingFang-SC;
            font-weight: 800;
            font-size: 26rpx;
            color: #FF4E70;
            line-height: 37rpx;
            text-align: left;
            font-style: normal;
          }
          
          .row-3{
            margin-top: 20rpx;
            font-family: PingFang-SC, PingFang-SC;
            font-weight: bold;
            font-size: 24rpx;
            color: #FFFFFF;
            line-height: 33rpx;
            text-align: left;
            font-style: normal;
          }
          
        }
      
      
      .right-clock{
        background-size: 100% 100%;
        // position: relative;
        // margin-top: 180rpx;
        
        
        // width: 302rpx;
        // height: 164rpx;
        
        .content-left{
          // position: absolute;
          // bottom: -14rpx;
          // left: 3rpx;
          // right: 3rpx;
          margin-left: 100rpx;
          
          width: 296rpx;
          height: 58rpx;
          background: #61B9E4;
          background: rgba(176, 109, 76, 0.75);
          // box-shadow: 0rpx 2rpx 4rpx 0rpx #86CEE6;
          box-shadow: 0rpx 2rpx 4rpx 0rpx #C79659;
          border-radius: 12rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .tip-text{
            font-family: PingFang-SC, PingFang-SC;
            font-weight: 800;
            font-size: 26rpx;
            color: #FFFFFF;
            // text-shadow: 0px 2px 4px #0E8FCE;
            text-align: center;
            font-style: normal;
            
            margin-right: 12rpx;
          }
        }
      
        .time {
            align-items: center;
            display: flex;
            margin-bottom: 2rpx;
        
            &__custom {
                 width: 28rpx;
                 height: 40rpx;
                 background-size: 100% 100%;
                 border-radius: 5rpx;
                 line-height: 40rpx;
                 text-align: center;
            
                &__item {
                     ont-family: PingFangSC, PingFang SC;
                     font-weight: 500;
                     font-size: 29rpx;
                     color: #FFFFFF;
                     line-height: 40rpx;
                     text-align: left;
                     font-style: normal;
                 }
            }
            
            &__doc {
               font-family: PingFangSC, PingFang SC;
               font-weight: 500;
               font-size: 36rpx;
               color: #FFFFFF;
               line-height: 50rpx;
               text-shadow: 0px 2px 4px #FFFFFF;
               text-align: left;
               font-style: normal;
               
               display: inline-block;
               margin: auto 4rpx;
             }
            
            &__item {
                 color: #606266;
                 font-size: 15px;
                 margin-right: 4px;
             }
        }
      }
    }
  }

  .main-content-wrapper{
    width: 750rpx;
    box-sizing: border-box;
    // padding-top: 412rpx;
    height: auto;
  }
  
  .scroll-menu{
    height: 54rpx;
    padding-right: 120rpx;
    width: 750rpx;
  }
  .menu-wrapper-container{
    // position: absolute;
    // z-index: 6;
    // margin-bottom: 12rpx;
    // top: 390rpx;
    // margin-top: 28rpx;
    background-color: #fff;
    
    position: sticky;
    top: 0;
    z-index: 6;
    
  }
  .menu-wrapper {
  	width: 750rpx;
  	padding: 0 20rpx;
  	display: flex;
  	column-gap: 10rpx;
  	margin-top: 2rpx;
        // margin-top: 390rpx;

  
  	.menu-box,.menu-box-act {
      background-color: #FFFFFF;
      padding: 5rpx 24rpx 8rpx 24rpx;
      border-radius: 25rpx;
      
      word-break: keep-all;
      line-height: 37rpx;
      height: fit-content;
      display: flex;
      align-items: center;
      text-align: center;
      
      font-size: 26rpx;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: 500;
      color: #999999;
  	}
    .menu-box-act{
      font-size: 26rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #7ADA6E;
      position: relative;
      
      &::after{
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 50rpx;
        height: 4rpx;
        background: #7ADA6E;
        border-radius: 2rpx;
      }
    }
    
    .menu-box-act-2::after{
      background-color: rgba(102, 102, 102, 1);
      bottom:1px;
    }
    
    
    .clear-padding{
      padding: 0;
    }
    
    .menu-item-bg{
      background: linear-gradient( 180deg, #FFFFFF 0%, #E5FFDC 100%);
      box-shadow: 0rpx 2rpx 10rpx 0rpx #CBF6BD;
      color: #666666;
      border-radius: 25rpx;
    }
    
  }
  
  // .menu-wrapper ==== end
</style>